package com.gouldzd.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.gouldzd.constant.MessageConstant;
import com.gouldzd.constant.RedisMessageConstant;
import com.gouldzd.entity.Result;
import com.gouldzd.pojo.Order;
import com.gouldzd.service.OrderService;
import com.gouldzd.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/*
 * @Author zhangdan
 * @Description //TODO 体检预约处理
 * @Date 17:32 2020/5/3
 * @Param
 * @return
 **/
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;

    //在线体检预约处理
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){

        //获取手机号
        String telephone = (String) map.get("telephone");
        //从redis中获取保存的验证码
        String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);

        //获取用户提交的验证码
        String validateCode = (String) map.get("validateCode");

        //将用户输入的验证码和redis中保存的验证码进行对比
        if(validateCode != null && validateCodeInRedis != null && validateCode.equals(validateCodeInRedis)){
            //如果比对成功,调用服务完成预约处理
            //设置预约类型:微信/电话预约
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            Result result = null;
            try {
                result = orderService.order(map);//通过dubbo远程调用服务实现在线预约业务处理
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false,"预约失败,服务器正忙");
            }

            //判断返回的falg
            if(result.isFlag()){
                //预约成功,可以为用户发送短信
                try {
                    SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone, (String) map.get("orderDate"));
                } catch (ClientException e) {
                    e.printStackTrace();
                }
            }

            //预约成功返回对象给前端
            return result;

        }else {
            //如果比对不成功,返回结果给页面
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

    }

    //根据预约id查询预约相关信息
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Map map = orderService.findById(id);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }

    }
}
